package com.example.design.limit;

import java.util.Collections;

//import org.junit.Assert;
//import org.junit.Test;
import org.redisson.Redisson;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.client.codec.Codec;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.RedissonNodeConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import com.jstarcraft.core.utility.StringUtility;
//import com.lenovoconnect.application.common.limiter.PriorityLimiter;
//import com.lenovoconnect.application.common.limiter.PriorityTask;

public class PriorityLimiterTestCase {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

//    @Test
    public void testLimiter() {
        // 注意此处的编解码器
        Codec codec = new JsonJacksonCodec();
        Config redisConfiguration = new Config();
        redisConfiguration.setCodec(codec);
        redisConfiguration.useSingleServer().setAddress("redis://127.0.0.1:6379");
        Redisson redisson = null;
        RedissonNodeConfig nodeConfiguration = new RedissonNodeConfig(redisConfiguration);
        nodeConfiguration.setExecutorServiceWorkers(Collections.singletonMap("test", 1));

        try {
            redisson = (Redisson) Redisson.create(redisConfiguration);
            RRateLimiter rateLimiter = redisson.getRateLimiter("limiter");
            rateLimiter.trySetRate(RateType.OVERALL, 200, 1, RateIntervalUnit.SECONDS);

            PriorityLimiter<String> priorityLimiter = new PriorityLimiter<>(200, 1000, rateLimiter::acquire);
            priorityLimiter.execute(new PriorityTask<>(5, () -> {
                return "第五优先级";
            }));
            priorityLimiter.execute(new PriorityTask<>(1, () -> {
                return "第一优先级";
            }));
        } catch (Exception exception) {
//            logger.error(StringUtility.EMPTY, exception);
//            Assert.fail();
        } finally {
            redisson.shutdown();
        }
    }

}
